#!/bin/bash
# macOS 完整网络配置备份脚本
# 备份所有网络配置到统一目录结构
# 使用方法: chmod +x complete_network_backup.sh && ./complete_network_backup.sh

# 设置备份目录
BASE_BACKUP_DIR="/Users/m/Downloads/netWorkBackUp"
BACKUP_DIR="$BASE_BACKUP_DIR/netWork-backup-$(date +%y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"

echo "=========================================="
echo "macOS 完整网络配置备份工具"
echo "=========================================="
echo "备份目录: $BACKUP_DIR"
echo "开始时间: $(date)"
echo "=========================================="

# 1. 备份网络接口配置
echo "1. 备份网络接口配置..."
ifconfig -a > "$BACKUP_DIR/ifconfig.txt"
networksetup -listallnetworkservices > "$BACKUP_DIR/network_services.txt"

# 备份每个网络服务的详细配置
echo "   备份网络服务详细配置..."
networksetup -listallnetworkservices | tail -n +2 | while read service; do
    if [ ! -z "$service" ]; then
        echo "   - 备份服务: $service"
        networksetup -getinfo "$service" > "$BACKUP_DIR/service_${service// /_}.txt"
        
        # 备份每个服务的代理设置
        networksetup -getwebproxy "$service" > "$BACKUP_DIR/proxy_web_${service// /_}.txt" 2>/dev/null
        networksetup -getsecurewebproxy "$service" > "$BACKUP_DIR/proxy_secure_${service// /_}.txt" 2>/dev/null
        networksetup -getsocksfirewallproxy "$service" > "$BACKUP_DIR/proxy_socks_${service// /_}.txt" 2>/dev/null
        networksetup -getftpproxy "$service" > "$BACKUP_DIR/proxy_ftp_${service// /_}.txt" 2>/dev/null
        networksetup -getproxybypassdomains "$service" > "$BACKUP_DIR/proxy_bypass_${service// /_}.txt" 2>/dev/null
    fi
done

# 2. 备份DNS配置
echo "2. 备份DNS配置..."
scutil --dns > "$BACKUP_DIR/dns_config.txt"
cat /etc/resolv.conf > "$BACKUP_DIR/resolv_conf.txt"

# 备份每个服务的DNS设置
echo "   备份各服务DNS设置..."
networksetup -listallnetworkservices | tail -n +2 | while read service; do
    if [ ! -z "$service" ]; then
        networksetup -getdnsservers "$service" > "$BACKUP_DIR/dns_${service// /_}.txt" 2>/dev/null
        networksetup -getsearchdomains "$service" > "$BACKUP_DIR/search_domains_${service// /_}.txt" 2>/dev/null
    fi
done

# 3. 备份路由表
echo "3. 备份路由表..."
netstat -rn > "$BACKUP_DIR/routing_table.txt"
arp -a > "$BACKUP_DIR/arp_table.txt"

# 4. 备份防火墙设置
echo "4. 备份防火墙设置..."
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate > "$BACKUP_DIR/firewall_state.txt" 2>/dev/null
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --listapps > "$BACKUP_DIR/firewall_rules.txt" 2>/dev/null

# 5. 备份hosts文件
echo "5. 备份hosts文件..."
cp /etc/hosts "$BACKUP_DIR/hosts.txt"

# 6. 备份网络位置信息
echo "6. 备份网络位置信息..."
networksetup -listlocations > "$BACKUP_DIR/network_locations.txt"
networksetup -getcurrentlocation > "$BACKUP_DIR/current_location.txt"

# 7. 备份系统网络配置（需要sudo权限）
echo "7. 备份系统网络配置..."
if [ "$EUID" -eq 0 ]; then
    # 以root权限运行
    echo "   使用管理员权限备份SystemConfiguration..."
    if [ -d "/Library/Preferences/SystemConfiguration" ]; then
        cp -r "/Library/Preferences/SystemConfiguration" "$BACKUP_DIR/"
        chown -R $(logname) "$BACKUP_DIR/SystemConfiguration" 2>/dev/null
        echo "   ✅ SystemConfiguration目录已备份"
    else
        echo "   ❌ SystemConfiguration目录不存在"
    fi
    
    # 备份其他系统配置
    [ -f "/etc/ppp/options" ] && cp /etc/ppp/options "$BACKUP_DIR/ppp_options.txt" 2>/dev/null
    [ -f "/etc/krb5.conf" ] && cp /etc/krb5.conf "$BACKUP_DIR/krb5_conf.txt" 2>/dev/null
    [ -f "/etc/ssh/ssh_config" ] && cp /etc/ssh/ssh_config "$BACKUP_DIR/ssh_config.txt" 2>/dev/null
else
    echo "   ⚠️  需要管理员权限备份SystemConfiguration目录"
    echo "   请运行: sudo $0 来获取完整备份"
fi

# 8. 记录Redis服务器信息
echo "8. 记录Redis服务器信息..."
REDIS_HOST="test-redis.oyumwu.clustercfg.apne1.cache.amazonaws.com"
cat > "$BACKUP_DIR/redis_server_info.txt" << EOF
目标Redis服务器信息
==================
主机: $REDIS_HOST
端口: 6379
记录时间: $(date)

连接要求:
- 需要公钥认证
- 请先配置本地公钥
- 联系运维将公钥添加到服务器白名单

连接测试命令（配置公钥后使用）:
ping $REDIS_HOST
nc -z -v $REDIS_HOST 6379
telnet $REDIS_HOST 6379
EOF

# 9. 创建完整的恢复脚本
echo "9. 创建恢复脚本..."
cat > "$BACKUP_DIR/restore.sh" << 'EOF'
#!/bin/bash
# macOS 网络配置完整恢复脚本

echo "=========================================="
echo "macOS 网络配置恢复工具"
echo "=========================================="
echo "开始时间: $(date)"

# 检查是否以管理员权限运行
if [ "$EUID" -ne 0 ]; then
    echo "⚠️  此脚本需要管理员权限"
    echo "请使用: sudo ./restore.sh"
    exit 1
fi

echo "开始恢复网络配置..."

# 1. 恢复hosts文件
echo "1. 恢复hosts文件..."
if [ -f "hosts.txt" ]; then
    cp hosts.txt /etc/hosts
    echo "   ✅ hosts文件已恢复"
else
    echo "   ❌ 找不到hosts.txt文件"
fi

# 2. 恢复网络偏好设置
echo "2. 恢复网络偏好设置..."
if [ -d "SystemConfiguration" ]; then
    # 备份当前配置
    cp -r /Library/Preferences/SystemConfiguration "/Library/Preferences/SystemConfiguration.backup.$(date +%y%m%d_%H%M%S)"
    echo "   ✅ 当前配置已备份"
    
    # 恢复配置
    cp -r SystemConfiguration/* /Library/Preferences/SystemConfiguration/
    echo "   ✅ 网络偏好设置已恢复"
else
    echo "   ❌ 找不到SystemConfiguration目录"
fi

# 3. 恢复代理设置
echo "3. 恢复代理设置..."
restored_proxies=0

# 恢复HTTP代理
for proxy_file in proxy_web_*.txt; do
    if [ -f "$proxy_file" ]; then
        service_name=$(echo "$proxy_file" | sed 's/proxy_web_//' | sed 's/.txt$//' | sed 's/_/ /g')
        echo "   恢复 $service_name 的HTTP代理..."
        
        if grep -q "Enabled: Yes" "$proxy_file"; then
            server=$(grep "Server:" "$proxy_file" | cut -d' ' -f2)
            port=$(grep "Port:" "$proxy_file" | cut -d' ' -f2)
            if [ ! -z "$server" ] && [ ! -z "$port" ]; then
                networksetup -setwebproxy "$service_name" "$server" "$port"
                echo "     设置HTTP代理: $server:$port"
                ((restored_proxies++))
            fi
        else
            networksetup -setwebproxystate "$service_name" off
            echo "     禁用HTTP代理"
        fi
    fi
done

# 恢复HTTPS代理
for proxy_file in proxy_secure_*.txt; do
    if [ -f "$proxy_file" ]; then
        service_name=$(echo "$proxy_file" | sed 's/proxy_secure_//' | sed 's/.txt$//' | sed 's/_/ /g')
        echo "   恢复 $service_name 的HTTPS代理..."
        
        if grep -q "Enabled: Yes" "$proxy_file"; then
            server=$(grep "Server:" "$proxy_file" | cut -d' ' -f2)
            port=$(grep "Port:" "$proxy_file" | cut -d' ' -f2)
            if [ ! -z "$server" ] && [ ! -z "$port" ]; then
                networksetup -setsecurewebproxy "$service_name" "$server" "$port"
                echo "     设置HTTPS代理: $server:$port"
                ((restored_proxies++))
            fi
        else
            networksetup -setsecurewebproxystate "$service_name" off
            echo "     禁用HTTPS代理"
        fi
    fi
done

# 恢复SOCKS代理
for proxy_file in proxy_socks_*.txt; do
    if [ -f "$proxy_file" ]; then
        service_name=$(echo "$proxy_file" | sed 's/proxy_socks_//' | sed 's/.txt$//' | sed 's/_/ /g')
        echo "   恢复 $service_name 的SOCKS代理..."
        
        if grep -q "Enabled: Yes" "$proxy_file"; then
            server=$(grep "Server:" "$proxy_file" | cut -d' ' -f2)
            port=$(grep "Port:" "$proxy_file" | cut -d' ' -f2)
            if [ ! -z "$server" ] && [ ! -z "$port" ]; then
                networksetup -setsocksfirewallproxy "$service_name" "$server" "$port"
                echo "     设置SOCKS代理: $server:$port"
                ((restored_proxies++))
            fi
        else
            networksetup -setsocksfirewallproxystate "$service_name" off
            echo "     禁用SOCKS代理"
        fi
    fi
done

echo "   ✅ 已恢复 $restored_proxies 个代理配置"

# 4. 恢复其他系统配置
echo "4. 恢复其他系统配置..."
[ -f "ppp_options.txt" ] && cp ppp_options.txt /etc/ppp/options 2>/dev/null && echo "   ✅ PPP配置已恢复"
[ -f "krb5_conf.txt" ] && cp krb5_conf.txt /etc/krb5.conf 2>/dev/null && echo "   ✅ Kerberos配置已恢复"
[ -f "ssh_config.txt" ] && cp ssh_config.txt /etc/ssh/ssh_config 2>/dev/null && echo "   ✅ SSH配置已恢复"

# 5. 重启网络服务
echo "5. 重启网络服务..."
dscacheutil -flushcache
killall -HUP mDNSResponder
echo "   ✅ DNS缓存已刷新"

# 6. 重启网络接口
echo "6. 重启网络接口..."
networksetup -setairportpower en0 off 2>/dev/null
sleep 2
networksetup -setairportpower en0 on 2>/dev/null
echo "   ✅ Wi-Fi接口已重启"

echo "=========================================="
echo "✅ 网络配置恢复完成！"
echo "完成时间: $(date)"
echo "=========================================="
echo ""
echo "建议操作:"
echo "1. 重启系统以确保所有设置完全生效"
echo "2. 重启后测试网络连接"
echo "3. 验证代理设置是否正确"
echo "4. 测试Redis服务器连接（需要先配置公钥）"
echo ""
EOF

chmod +x "$BACKUP_DIR/restore.sh"

# 10. 创建备份验证脚本
echo "10. 创建备份验证脚本..."
cat > "$BACKUP_DIR/verify_backup.sh" << 'EOF'
#!/bin/bash
# 备份验证脚本

echo "=========================================="
echo "备份验证工具"
echo "=========================================="

# 检查必要文件
echo "检查必要文件..."
required_files=(
    "ifconfig.txt"
    "network_services.txt" 
    "dns_config.txt"
    "routing_table.txt"
    "hosts.txt"
    "redis_server_info.txt"
)

missing_files=()
for file in "${required_files[@]}"; do
    if [ -f "$file" ]; then
        echo "   ✅ $file"
    else
        echo "   ❌ $file"
        missing_files+=("$file")
    fi
done

# 检查SystemConfiguration目录
echo ""
echo "检查系统配置..."
if [ -d "SystemConfiguration" ]; then
    config_count=$(ls SystemConfiguration 2>/dev/null | wc -l)
    echo "   ✅ SystemConfiguration目录已备份 ($config_count 个文件)"
else
    echo "   ⚠️  SystemConfiguration目录未备份（可能需要sudo权限）"
fi

# 统计代理配置文件
echo ""
echo "检查代理配置..."
proxy_files=$(ls proxy_*.txt 2>/dev/null | wc -l)
if [ $proxy_files -gt 0 ]; then
    echo "   ✅ 备份了 $proxy_files 个代理配置文件"
    
    # 显示代理状态
    enabled_proxies=0
    for proxy_file in proxy_*.txt; do
        if [ -f "$proxy_file" ] && grep -q "Enabled: Yes" "$proxy_file"; then
            ((enabled_proxies++))
        fi
    done
    echo "   📊 其中 $enabled_proxies 个代理处于启用状态"
else
    echo "   ❌ 未找到代理配置文件"
fi

# 检查DNS配置
echo ""
echo "检查DNS配置..."
dns_files=$(ls dns_*.txt 2>/dev/null | wc -l)
if [ $dns_files -gt 0 ]; then
    echo "   ✅ 备份了 $dns_files 个DNS配置文件"
else
    echo "   ❌ 未找到DNS配置文件"
fi

# 总结
echo ""
echo "=========================================="
if [ ${#missing_files[@]} -eq 0 ]; then
    echo "✅ 备份验证通过！所有重要配置都已备份"
else
    echo "⚠️  备份不完整，缺少以下文件:"
    for file in "${missing_files[@]}"; do
        echo "   - $file"
    done
fi
echo "=========================================="
EOF

chmod +x "$BACKUP_DIR/verify_backup.sh"

# 11. 创建备份信息文件
echo "11. 创建备份信息文件..."
cat > "$BACKUP_DIR/README.md" << EOF
# macOS 网络配置备份

## 备份信息
- **备份时间**: $(date)
- **备份目录**: $BACKUP_DIR
- **脚本版本**: 完整版 v2.0

## 备份内容

### 网络配置
- \`ifconfig.txt\` - 网络接口信息
- \`network_services.txt\` - 网络服务列表
- \`service_*.txt\` - 各网络服务详细配置

### 代理设置
- \`proxy_web_*.txt\` - HTTP代理配置
- \`proxy_secure_*.txt\` - HTTPS代理配置
- \`proxy_socks_*.txt\` - SOCKS代理配置
- \`proxy_ftp_*.txt\` - FTP代理配置
- \`proxy_bypass_*.txt\` - 代理绕过域名

### DNS配置
- \`dns_config.txt\` - 系统DNS配置
- \`resolv_conf.txt\` - resolv.conf文件
- \`dns_*.txt\` - 各服务DNS设置
- \`search_domains_*.txt\` - 搜索域设置

### 系统配置
- \`SystemConfiguration/\` - 系统网络配置目录
- \`hosts.txt\` - hosts文件
- \`routing_table.txt\` - 路由表
- \`arp_table.txt\` - ARP表

### 其他信息
- \`network_locations.txt\` - 网络位置列表
- \`current_location.txt\` - 当前网络位置
- \`redis_server_info.txt\` - Redis服务器信息

## 使用方法

### 验证备份
\`\`\`bash
./verify_backup.sh
\`\`\`

### 恢复配置
\`\`\`bash
sudo ./restore.sh
\`\`\`

### 重启系统
恢复后建议重启系统以确保所有设置生效

## Redis连接信息
- **服务器**: test-redis.oyumwu.clustercfg.apne1.cache.amazonaws.com
- **端口**: 6379
- **认证**: 需要公钥认证
- **注意**: 请先配置本地公钥并联系运维添加到白名单

## 注意事项
1. 恢复操作需要管理员权限 (sudo)
2. 建议恢复前再次备份当前配置
3. 恢复后需要重启系统
4. 如遇问题可手动恢复各配置文件
EOF

# 12. 统计备份结果
echo "12. 统计备份结果..."
total_files=$(find "$BACKUP_DIR" -type f | wc -l)
backup_size=$(du -sh "$BACKUP_DIR" | cut -f1)

echo ""
echo "=========================================="
echo "✅ 完整备份完成！"
echo "=========================================="
echo "备份位置: $BACKUP_DIR"
echo "备份文件: $total_files 个文件"
echo "备份大小: $backup_size"
echo "完成时间: $(date)"
echo "=========================================="
echo ""
echo "后续操作:"
echo "1. 验证备份: cd '$BACKUP_DIR' && ./verify_backup.sh"
echo "2. 查看说明: cd '$BACKUP_DIR' && cat README.md"
echo "3. 恢复配置: cd '$BACKUP_DIR' && sudo ./restore.sh"
echo ""
echo "Redis服务器: test-redis.oyumwu.clustercfg.apne1.cache.amazonaws.com"
echo "注意: 需要先配置公钥认证才能连接"
echo ""
